﻿using System;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Collections;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
       
        public string workingDir="";
        public string htmlFile="";
        public string enFile="";
        public int langIndex = 0;
        public bool STOP=false;
        public ArrayList langs = new ArrayList();
        public class lang {
                 public string Name;
            public string langCode;
       
            public lang(string n, string i) {
                Name = n; 
                langCode = i;
               
            
            }
        }
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            STOP = false;
            textBox4.Clear();

            if (checkBox1.Checked)
            {
                lang l = (lang)langs[langIndex];
                    if (!STOP) translateMSGbundle(l.langCode);
            } else {
                if (comboBox1.SelectedItem == null) { MessageBox.Show("select a language to translate from dropdown list"); return; }
                string langCode="";
            foreach (lang l in langs)
                if (l.Name == comboBox1.SelectedItem.ToString()) {langCode = l.langCode; break;}
                translateMSGbundle(langCode);}
            label1.Text = "";
        }
        

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            textBox1.Text = "loaded file-" + openFileDialog1.FileName;
            htmlFile = openFileDialog1.FileName;
            workingDir = Path.GetDirectoryName(openFileDialog1.FileName)+"\\";
             textBox2.Text = openFileDialog1.FileName;
            button5.Enabled = true;
            if (enFile != "") button2.Enabled = true;

          
        }
        public void translateMSGbundle(string langCode) {
            button1.Enabled = false;
            button6.Visible = true;
            label1.Text = "Now translating for " + langCode + ", done:0%";
            progressBar1.Value = 0;
            progressBar1.Visible = true;
            progressBar1.Maximum = 100;
            progressBar1.Style = ProgressBarStyle.Continuous;
            backgroundWorker1.RunWorkerAsync(langCode);
            
        }
      
        private void button2_Click(object sender, EventArgs e)
        {
            progressBar1.Visible = true;
            progressBar1.Value = 5;
            
            TextReader tr = new StreamReader(htmlFile);
            string content = tr.ReadToEnd(); tr.Close();
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(enFile);
            XmlNodeList list = xDoc.GetElementsByTagName("msg");
            int i = 0;
            while (i < list.Count)
            {
                string id = list[i].Attributes[0].Value;
                string text = list[i].InnerText;

                content = Regex.Replace(content, @"(>\s*)" + Regex.Escape(text) + @"(\s*<)", "$1__MSG_" + id + "__$2");
               
                i++;
            }
            string outputFile = workingDir + Path.GetFileNameWithoutExtension(htmlFile) + "_i18n" + Path.GetExtension(htmlFile);
          textBox1.Text+="\r\n"+i+" replacements made, saved in  "+outputFile;
                TextWriter tw = new StreamWriter(outputFile);
            tw.Write(content);
            tw.Close();
            progressBar1.Visible = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
          
              langs.Add(new lang("Arabic","ar"));
             langs.Add(new lang("Bulgarian", "bg"));
             langs.Add(new lang("Chinese (Simplified)", "zh-CN"));
             langs.Add(new lang("Chinese (Traditional)", "zh-TW"));
             langs.Add(new lang("Croatian", "hr"));
             langs.Add(new lang("Czech", "cs"));
             langs.Add(new lang("Danish", "da"));
            langs.Add(new lang("Dutch", "nl"));
             langs.Add(new lang("Finnish", "fi"));
            langs.Add(new lang("French", "fr"));
             langs.Add(new lang("Greek", "el"));
             langs.Add(new lang("Hindi", "hi"));
             langs.Add(new lang("Italian", "it"));
             langs.Add(new lang("Japanese", "ja"));
            langs.Add(new lang("Korean", "ko"));
             langs.Add(new lang("Norwegian", "no"));
             langs.Add(new lang("Polish", "pl"));
             langs.Add(new lang("Portuguese", "pt"));
             langs.Add(new lang("Romanian", "ro"));
             langs.Add(new lang("Russian", "ru")); 
             langs.Add(new lang("Spanish", "es"));
             langs.Add(new lang("Swedish", "sv"));

            foreach (lang l in langs)
                comboBox1.Items.Add(l.Name);
            //button3.Focus();
            textBox1.Text = "No HTML file loaded, select a html file with no <script> tags,primarily text elements in it.\r\n\t OR \r\nSelect an existing english message bundle to be translated";
            textBox1.SelectionLength = 0;
            button3.Focus();
          
        }

        private void button3_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //GENERATE ENGLISH MESSAGE BUNDLE FROM HTML
            progressBar1.Visible = true;
            progressBar1.Value = 5;
            progressBar1.Style = ProgressBarStyle.Marquee;
            TextReader tr = new StreamReader(htmlFile);
            enFile=workingDir + "en_ALL.xml";
            TextWriter tw = new StreamWriter(enFile);
            textBox3.Text = enFile;
            tw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            tw.WriteLine("<messagebundle>");
            int count = 0;
            int ascii;
            char buffer;
            ArrayList texts = new ArrayList();
            ascii = tr.Read();

            string content = "";
            bool parseStart = false;
            while (ascii > -1)
            {
                buffer = (char)ascii;
                //MessageBox.Show(buffer.ToString());
                if (buffer == '\r')
                {
                    tr.Read(); ascii = tr.Read();
                    continue;
                }
                if (buffer == '>')
                {
                    parseStart = true; ascii = tr.Read();
                    continue;
                }
                if (buffer == '<')
                {
                    parseStart = false; ascii = tr.Read();
                    continue;
                }

                if (parseStart) content += buffer;
                else
                {
                    string str = content.Trim();
                    double Num;
                    bool isNum = double.TryParse(str, out Num);
                    Regex pattern = new Regex("[a-zA-Z]");
                    Match m;
                    m = pattern.Match(str);

                    if (str != "" && m.Success && texts.IndexOf(str) < 0)
                    {
                        tw.WriteLine("<msg name='str" + count + "'><![CDATA[" + str + "]]></msg>");
                        texts.Add(str);
                        count++;
                    }
                    content = "";
                }
                ascii = tr.Read();
            }
            tr.Close();
            tw.WriteLine("</messagebundle>");
            tw.Close();
            textBox1.Text = textBox1.Text + "\r\nwrote " + count + " lines in " + workingDir + "en_ALL.xml";
            progressBar1.Value = 0;
            progressBar1.Visible = false;
            button2.Enabled = true;
            button1.Enabled = true;
            comboBox1.Enabled = true;
            checkBox1.Enabled = true;
            langIndex = 0;
        }

        private void button4_Click(object sender, EventArgs e)
        {
                        openFileDialog2.ShowDialog();
        }

        private void openFileDialog2_FileOk(object sender, CancelEventArgs e)
        {
            enFile = openFileDialog2.FileName;
            textBox3.Text = enFile;
            workingDir = Path.GetDirectoryName(enFile)+"\\";
            textBox1.Text = "\r\nloaded en message bundle:" + enFile;
            button1.Enabled = true;
            if(htmlFile!="")button2.Enabled = true;
            comboBox1.Enabled = true;
            checkBox1.Enabled = true;
            langIndex = 0;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true) comboBox1.Enabled = false; else comboBox1.Enabled = true; ;

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string langCode = e.Argument as string;
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(enFile);
            XmlNodeList list = xDoc.GetElementsByTagName("msg");
            TextWriter tw = new StreamWriter(workingDir + langCode.Replace('-', '_') + "_ALL.xml");
            tw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            tw.WriteLine("<messagebundle>");
            int i = 0;
            while (i < list.Count)
            {
                if (backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true; tw.WriteLine("</messagebundle>");
                    tw.Close(); return;
                }
                string id = list[i].Attributes[0].Value;
                string text = list[i].InnerText;
                try
                {
                    string url = String.Format("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q={0}&langpair=en%7C{1}", HttpUtility.UrlEncode(text), langCode);
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    TextReader tr = new StreamReader(response.GetResponseStream());
                    string translatedText =tr.ReadToEnd().Remove(0, 36);
                    translatedText = translatedText.Remove(translatedText.IndexOf("\"}"));
                    translatedText = System.Web.HttpUtility.HtmlDecode(translatedText);
                    tw.WriteLine("<msg name='" + id + "'><![CDATA[" + translatedText + "]]></msg>");
                    int progress = (i * 100) / list.Count;
                    i++;
                    backgroundWorker1.ReportProgress(progress, langCode);
                }
                catch (Exception Ex) { MessageBox.Show(Ex.Message.ToString()); STOP = true; backgroundWorker1.CancelAsync(); }
                
                
            }
            tw.WriteLine("</messagebundle>");
            tw.Close();
            e.Result = langCode;
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label1.Text = "Now fetching translations for '" + e.UserState + "' language code, completed:" + e.ProgressPercentage + "%";
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                label1.Text = "Process Cancelled by user";
                progressBar1.Visible = false;
                button1.Enabled = true;
                button6.Visible = false;
            }
            else {
                string langCode=e.Result.ToString().Replace('-', '_');
                label1.Text = "Completed generating " + langCode + " message bundle";
                textBox1.Text = textBox1.Text + "\r\nsuccessfully generated " + workingDir+langCode + "_ALL.xml";
                string server = textBox5.Text;
                if(server.Length>0)server=server[server.Length-1]=='/' ? server : server+'/'; 
                textBox4.Text += "<Locale lang=\"" + langCode + "\" messages=\"" + server + langCode + "_ALL.xml\"/>\r\n";
            }
            if (checkBox1.Checked && langIndex < (langs.Count-1)) { if (!STOP) { langIndex++; lang temp = (lang)langs[langIndex]; translateMSGbundle(temp.langCode); } }
            else
            {
                progressBar1.Visible = false;
                button1.Enabled = true;
                button6.Visible = false;
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            STOP = true;
            backgroundWorker1.CancelAsync();
                    }

       
        
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            linkLabel2.Links.Add(0, 25, @"http://code.google.com/p/osi18ntool/");
            Process linkLabelProc = new Process();
            linkLabelProc.StartInfo.FileName = linkLabel2.Links[0].LinkData.ToString();
            linkLabelProc.StartInfo.Arguments = null;
            linkLabelProc.Start();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            linkLabel1.Links.Add(0, 12, @"http://aakash.me");
            Process linkLabelProc = new Process();
            linkLabelProc.StartInfo.FileName = linkLabel1.Links[0].LinkData.ToString();
            linkLabelProc.StartInfo.Arguments = null;
            linkLabelProc.Start();
        }

      

        private string GetFilename(DragEventArgs e)
        {
          
            string filename = String.Empty;

            if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
            {
                Array data = ((IDataObject)e.Data).GetData("FileName") as Array;
                if (data != null)
                {
                    if ((data.Length == 1) && (data.GetValue(0) is String))
                    {
                        filename = ((string[])data)[0];
                       
                    }
                }
            }
            return filename;
        }

      

        private void textBox2_DragEnter(object sender, DragEventArgs e)
        {
            string fileName = GetFilename(e);
            if (Path.GetExtension(fileName).ToLower() == ".txt" || Path.GetExtension(fileName).ToLower() == ".html" || Path.GetExtension(fileName).ToLower() == ".htm")
            {
                textBox1.Text = "loaded file-" + fileName;
                htmlFile = fileName;
                workingDir = Path.GetDirectoryName(fileName) + "\\";
                textBox2.Text = fileName;
                button5.Enabled = true;
                if (enFile != "") button2.Enabled = true;
            }
        }

        private void textBox3_DragEnter(object sender, DragEventArgs e)
        {
            string fileName = GetFilename(e);

            enFile = fileName;
            textBox3.Text = enFile;
            workingDir = Path.GetDirectoryName(enFile) + "\\";
            textBox1.Text = "\r\nloaded en message bundle:" + enFile;
            button1.Enabled = true;
            if (htmlFile != "") button2.Enabled = true;
            comboBox1.Enabled = true;
            checkBox1.Enabled = true;
            langIndex = 0;
        }
        
      

        
        
    }
}
